<?php

set_include_path('.' . PATH_SEPARATOR . '../library' . PATH_SEPARATOR . get_include_path());
define('APP_DIR', realpath('../application'));

class LayeredContent
{
	public $dev = true;
	public $useWWW = true;
	public $isWWW;
	public $server;
	public $uri;
	public $path;
	
	public function dispatch()
	{
		$this->parseUrl();
		
		$this->fixWWW();
		
		if ($this->deliverCache()) {
			return;
		}
		
		$this->deliverPage();
	}
	
	public function parseUrl()
	{
		$this->server = preg_replace('/^www\./', "", $_SERVER["HTTP_HOST"], -1, $this->isWWW);
		
		// take off first slash and ending slash or .html
		$this->request = preg_replace('~^/|(/|\.\w+)?(\?.*)?$~', "", $_SERVER["REQUEST_URI"]);
		
		$this->path = $this->request ? "$this->server/$this->request" : $this->server;
	}
	
	public function fixWWW()
	{
		if (!$this->useWWW && $this->isWWW) {
			$this->permanentRedirect("http://$this->server" . $_SERVER["REQUEST_URI"]);
		} elseif ($this->useWWW && !$this->isWWW) {
			$this->permanentRedirect("http://www.$this->server" . $_SERVER["REQUEST_URI"]);
		}
	}
	
	public function deliverCache()
	{
	
//		require_once INCLUDES . "blueprint/Blueprint.php";
//		
//		$BLUEPRINT_TEMPLATES_DIR = TEMPLATES;
//		$BLUEPRINT_CACHE_DIR = CACHE;
//		$BLUEPRINT_WEBROOT = preg_replace('|index.php.*$|', "", $_SERVER['PHP_SELF']);
//		
//		// Show the cached version if it is current
//		$cache = $BLUEPRINT_CACHE_DIR . $path . ".cache";
//		if (!DEV && !$isAdmin && CachedTemplate::validCache($cache, 5)) {
//			readfile($cache);
//			exit;
//		} elseif (DEV) {
//			@unlink($cache);
//		}
	}
	
	public function deliverPage()
	{
		// load needed libraries to show the page
		require_once "Zend/Db/ActiveRecord/Gateway.php";
		require_once APP_DIR . "/models/Page.php";
		require_once APP_DIR . "/models/Revision.php";
		require_once APP_DIR . "/models/Content.php";
		require_once APP_DIR . "/models/Template.php";
		require_once APP_DIR . "/models/Field.php";
		
		
		
//		// load up plugins
//		$plugins = array();
//		$dir = new DirectoryIterator(PLUGINS);
//		foreach ($dir as $file) {
//			if ($file->isFile()) {
//				if (preg_match('/^(\w+)\.php$/', $file->getFilename(), $matches)) {
//					$classname = $matches[1];
//					require_once $file->getPathname();
//					if (class_exists($classname))
//						$plugins[] = new $classname();
//				}
//			}
//		}
//		
//		$page = Page::findFirst(array("path = ?", $path));
//		
//		if (!$page) // TODO, show custom page not found page
//			pageNotFound("This page does not exist in the database");
//		
//		if ($page->redirect_id) {
//			$redirectPage = new Page($page->redirect_id);
//			permanentRedirect("http://$redirectPage->path");
//		}
//		
//		$page->loadRevisions(null, "created");
//		
//		if ($isAdmin && isset($_GET["draft"])) {
//			$revision = $page->revisions[count($page->revisions) - 1];
//		} else {
//			$revision = $page->getRevision(null, $isAdmin);
//		}
//		
//		if (!$revision) // TODO, show custom page not found page
//			pageNotFound("This page exists but has no published revisions");
//		
//		$template = $revision->loadTemplate();
//		
//		if (!$template)
//			pageNotFound("The template for this page was not found");
//		
//		$view = new Blueprint($template->pageFile, $template->layoutFile || $isAdmin ? null : $cache);
//		$view->assign("page", $page);
//		
//		if ($template->layoutFile) {
//			$layout = new Blueprint($template->layoutFile, $isAdmin ? null : $cache);
//			$layout->assign("page", $page);
//		}
//		
//		// breadcrumbs
//		$breadcrumbs = split("/", $path);
//		array_shift($breadcrumbs);
//		//array_pop($breadcrumbs);
//		$view->assign("breadcrumbs", $breadcrumbs);
//		if ($layout)
//			$layout->assign("breadcrumbs", $breadcrumbs);
//		
//		$fields = $template->loadFields();
//		
//		if ($isAdmin && isset($_GET["draft"]))
//			$page->loadContentsByRevision($revision->id);
//		else
//			$page->loadContents();
//		
//		foreach ($fields as $field) {
//			
//			$content = "";
//			
//			foreach ($page->contents as $contentObj) {
//				if ($contentObj->field == $field->name) {
//					$content = $contentObj->value;
//					break;
//				}
//			}
//			
//			if (!$content)
//				$content = $field->content;
//					
//			foreach ($plugins as $plugin) {
//				if (method_exists($plugin, "handleContent")) {
//					$content = $plugin->handleContent($content);
//				}
//			}
//			
//			if ($isAdmin && $field->name != "title")
//				$content = "<cms name=\"$field->name\" type=\"$field->type\">$content</cms>";
//			
//			$view->assign($field->name, $content);
//			if ($layout)
//				$layout->assign($field, $content);
//		}
//		
//		$output = $view->fetch();
//		
//		if ($layout) {
//			$layout->assign("pageContent", $output);
//			$output = $layout->fetch();
//		}
//		
//		foreach ($plugins as $plugin) {
//			if (method_exists($plugin, "handleOutput")) {
//				$output = $plugin->handleOutput($output);
//			}
//		}
//		
//		echo $output;
		
		
		
		
		
		
		
		
	}
	

	public function permanentRedirect($url) {
		header("HTTP/1.1 301 Moved Permanently");
		header("Location: $url");
		exit;
	}
	
	public function pageNotFound($message = null) {
		header("HTTP/1.1 404 Page Not Found");
		readfile(TEMPLATES . "404.html");
		
		if ($message && DEV)
			echo "<font style='font-weight:bold;color:red'>$message</font>";
		exit;
	}
}



